package com.bizmda.bizsip.sample.source.longtcpnetty;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bizmda.bizsip.common.BizConstant;
import com.bizmda.bizsip.common.BizUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: 史正烨
 * @Date: 2022/3/1 11:11 上午
 * @Description:
 */
@Service
@Slf4j
public class SampleServerService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void process(SampleMessage sampleMessage) {
        if (sampleMessage.getLength() == 0) {
            log.debug("收到心跳检测包!");
            return;
        }
        log.debug("收到报文(长度:{}):\n{}",
                sampleMessage.getLength(), BizUtils.buildHexLog(sampleMessage.getData()));
        JSONObject jsonObject;
        try {
            jsonObject = JSONUtil.parseObj(new String(sampleMessage.getData(),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("码制转换失败!",e);
            return;
        }
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.set("app-service-id","/bean/sample1");
        jsonObject1.set("data",jsonObject);
        Message message = MessageBuilder.withBody(JSONUtil.toJsonStr(jsonObject1).getBytes(StandardCharsets.UTF_8))
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setReplyTo("queue.bizsip.longtcp").build();
        this.rabbitTemplate.send(BizConstant.APP_SERVICE_EXCHANGE, BizConstant.APP_SERVICE_ROUTING_KEY, message);
    }
}
